# -*- encoding:utf-8 -*-
"""
@作者：ven
@文件名：baseApi.py
@时间：2021-11-15  9:26
@文档说明:
"""
import inspect
import traceback

import requests, os
from faker import Faker

from config.config import HOST
from utils.loguruUtil import log
# from utils.mysqlUtil import MysqlConnectDatabase
from utils.pathUtil import config_path
from utils.yamlUtil import get_yaml_data, get_yaml_case_data


class BaseAPI:
    def __init__(self, inToken=None):
        '''
        1.获取调用类的类名,self.className = self.__class__.__name__
        2.读取配置文件,获取调用类的所有数据
        3.所有的业务类都需要使用token,这里需要传入一个token
        '''

        if inToken:
            self.headers = {'token': inToken, 'X-Requested-With': 'XMLHttpRequest'}
        else:
            self.headers = None
        self.className = self.__class__.__name__
        self.data = get_yaml_data(os.path.join(config_path, 'api.yaml'))[self.className]

    def request_send(self, id='', **kwargs):
        '''
        1.获取调用该方法的方法名，获取具体方法的method和path
        '''
        try:
            funcName = inspect.stack()[1][3]
            method, path = self.data[funcName].values()

            url = os.path.join(HOST, path + str(id)).replace('\\', '/')

            return requests.request(method=method, url=url, verify=False, headers=self.headers, **kwargs)
        except Exception as error:
            log.error(traceback.format_exc())
            raise error

    '''
    1- 增删改查方法是四个基础方法，定义在基类中，供业务模块进行调用，业务模块减少代码冗余
    '''

    def add(self, **kwargs):
        return self.request_send(**kwargs)

    def delete(self, delId):
        log.info(f'删除ID:{delId}')
        return self.request_send(id=delId)

    def update(self, **kwargs):
        return self.request_send(**kwargs)

    def query(self, **kwargs):
        # TODO 根据业务修改这里的代码
        return self.request_send(**kwargs)

    def delete_all(self):
        # 1. 调查询接口
        # 2. 根据查询到的id删除所有项（类似于部门，需要重新处理，总部门不能删除）
        # TODO
        return

    def upload(self, **kwargs):
        return self.request_send(**kwargs)


class ApiAssert:
    '''封装断言方法+异常处理'''
    @classmethod
    def define_api_assert(self, expData, condition, res):
        try:
            if condition == '=':
                assert res == expData
            elif condition == 'in':
                assert expData in res
        except Exception as error:
            log.error(traceback.format_exc())
            raise error


# class WithMysqlCompare:
#     conn = MysqlConnectDatabase()
#
#     @classmethod
#     def is_exist(cls, sql, worker_id):
#         '''与数据库中的worker_id进行比较，目前实现判断已删除的人员id是否在base_worker_iris、face中能否查询到'''
#         worker_ids = []
#         try:
#             for item in list(cls.conn.query(sql)):
#                 worker_ids.append(item[0])
#             if int(worker_id) in worker_ids:
#                 return False
#             else:
#                 return True
#         except Exception as error:
#             log.error(traceback.format_exc())
#             raise error
#
#     @classmethod
#     def is_del(cls, sql):
#         '''根据删除标志查询,默认查询select del_flag from 表名称 where id = XX'''
#         try:
#             if cls.conn.query(sql)[0][0] == 1:
#                 return True
#             else:
#                 return False
#         except Exception as error:
#             log.error(traceback.format_exc())
#             raise error
